package com.choker.mall.interceptor;

import com.choker.mall.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Lychee on 2018/3/12 08:39.
 * <p>
 * Author:Hejingzhou
 * <p>
 * Email:tcowork@163.com
 */
public class CoustomHandlerInterceptor implements HandlerInterceptor {

    private static final String[] IgnoreUrlArray = {"/loginForm", "/login"};

    /**
     * 在Mapping 处理业务请求之前进行调用  返回true 继续向下执行，
     * 否则则中断向下传递  直接拦截  用于验证身份
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        System.out.println("preHandle()");
        boolean flag = false;
        String servletPath = httpServletRequest.getServletPath();
        for (String s : IgnoreUrlArray) {
            if (servletPath.contains(s)) {
                //如果是属于忽略URL中的那么直接不进行拦截校验
                flag = true;
                break;
            }
        }

        if (!flag) {
            User user = (User) httpServletRequest.getSession().getAttribute("user");
            if (user == null) {
                System.out.println("属于拦截请求");
                httpServletRequest.setAttribute("message", "请先登录再访问网站");
                httpServletRequest.getRequestDispatcher("loginForm").forward(httpServletRequest, httpServletResponse);
            } else {
                System.out.println("校验通过");
                flag = true;
            }
        }

        return flag;
    }

    /**
     * 在进入Mapping 处理业务模块之后 在 ModelAndView之前进行执行，
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param modelAndView
     * @throws Exception
     */
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle()");
    }

    /**
     * 最后执行
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param e
     * @throws Exception
     */
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("afterCompletion()");
    }
}
